package org.liuwei.concucrent.base03.Semaphore05;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Semaphore;

/**
 * 
 * @Title: TestSemaphore.java
 * @Package org.liuwei.concucrent.base03.ReentrantLock01.Semaphore05
 * @Description: TODO(申明了一个只有5个许可的Semaphore，
 *               而有20个线程要访问这个资源，通过acquire()和release()获取和释放访问许可)
 * @author 刘伟 15818570028@163.com
 * @date 2016年8月20日 下午8:57:21
 * @version V1.0
 */
public class TestSemaphore {

	public static void main(String[] args) {

		// 线程池

		ExecutorService exec = Executors.newCachedThreadPool();

		// 只能5个线程同时访问

		final Semaphore semp = new Semaphore(5);

		// 模拟20个客户端访问

		for (int index = 0; index < 20; index++) {

			final int no = index;

			Runnable run = new Runnable() {

				public void run() {

					try {

						// 获取许可

						semp.acquire();

						System.out.println("Accessing: " + no);

						Thread.sleep((long) (Math.random() * 1000));

						// 访问完后，释放

						semp.release();

						System.out.println("-----------------"
								+ semp.availablePermits());

					} catch (InterruptedException e) {

						e.printStackTrace();

					}

				}

			};

			exec.execute(run);

		}

		// 退出线程池

		exec.shutdown();

	}

}